package com.immortal.core.filters;

import com.alibaba.fastjson.JSONObject;
import com.immortal.core.filters.wrapper.RequestWrapper;
import com.immortal.core.filters.wrapper.ResponseWrapper;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * <p>TODO
 *
 * @author wind
 * @version 1.0
 * @since 2018/12/13
 */
public interface HttpTraceLogService {
    JSONObject traceLog(long startTime, HttpServletRequest request, HttpServletResponse response) throws IOException;


    default boolean isRequestValid(HttpServletRequest request) {
        try {
            new URI(request.getRequestURL().toString());
            return true;
        } catch (URISyntaxException ex) {
            return false;
        }
    }

    default String getRequestBody(HttpServletRequest request) {
        String requestBody = "";
        RequestWrapper wrapper=(RequestWrapper)request;
        if (wrapper != null) {
            try {
                requestBody = IOUtils.toString(wrapper.toByteArray(), wrapper.getCharacterEncoding());
            } catch (IOException e) {
                // NOOP
            }
        }
        return requestBody;
    }
    default String getResponseBody(HttpServletResponse response) {
        String responseBody = "";
       ResponseWrapper wrapper = (ResponseWrapper)response;
        if (wrapper != null) {
            try {
                responseBody = IOUtils.toString(wrapper.toByteArray(), wrapper.getCharacterEncoding());
            } catch (IOException e) {
                // NOOP
            }
        }
        return responseBody;
    }

    default boolean isBinaryContent(final HttpServletResponse response) {
        if (response.getContentType() == null) {
            return false;
        }
        return response.getContentType().startsWith("image")
                || response.getContentType().startsWith("video")
                || response.getContentType().startsWith("audio");
    }

    default boolean isMultipart(final HttpServletRequest request) {
        return request.getContentType() != null
                && MediaType.MULTIPART_FORM_DATA.includes(MediaType.parseMediaType(request.getContentType()));
    }

}
